<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Traits\ApiResponse;

class ApiAuth
{
    use ApiResponse;

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        try {
            if ( JWTAuth::parseToken()->authenticate() ) {
                return $next($request);
            }
            return $this->responseFailed(['message' => '未登录']);
        } catch ( TokenExpiredException $e ) {
            return $this->responseUnauthorized();
        } catch ( TokenInvalidException $e ) {
            return $this->responseUnauthorized();
        } catch ( JWTException $e ) {
            return $this->responseUnauthorized();
        }
    }
}
